package com.magicmovie.web.controller;

import com.magicmovie.entity.User;
import com.magicmovie.utils.AjaxMsg;
import com.magicmovie.web.service.DictionaryService;
import com.magicmovie.web.service.UserService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DictionaryService dictionaryService;

    @RequestMapping(value = "/list")
    public String list(Model model) {
        Map map = new HashMap<>();
        List list = userService.findByParams(map);
        model.addAttribute("list", list);
        return "user/list";
    }


    @RequestMapping(value = "/input")
    public String input(Model model, Integer id) {
        User user = userService.findByPrimaryKey(id);
        model.addAttribute("entity", user);
        return "user/input";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
//    @RequiresRoles("admin")
    public AjaxMsg save(User user) {
        if (user.getId() == null || user.getId() == 0) {
            if(userService.findByUserName(user.getUsername()) != null)
                return new AjaxMsg(AjaxMsg.FAILURE,"账号已存在！");
            userService.insert(user);
        } else {
            userService.update(user);
        }
        return new AjaxMsg();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
//    @RequiresRoles("admin")
    public AjaxMsg delete(Integer id) {
        userService.delete(id);
        return new AjaxMsg();
    }
}
